package Application.Widgets.Other;

import Application.Utils.StaticUtil;
import Application.Widgets.Override.ButtonOverride;
import Application.Widgets.TextFileds.TextFiledString;

import javax.swing.*;
import java.awt.*;

public class ListPanelForTags extends JPanel {
    private DefaultListModel<String> model = new DefaultListModel<>();
    private JList tagsList;
    private TextFiledString tf_tagName;
    private ButtonOverride addButton;
    private ButtonOverride deleteButton;
    private ButtonOverride editButton;

    public ListPanelForTags(JComponent component,JFrame frame) {
        super(new BorderLayout());
        this.setFont(StaticUtil.config.fontGetter());
        tagsList = new JList(model);
        tagsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        this.add(tagsList, BorderLayout.NORTH);
        tf_tagName = new TextFiledString("Null","Tag设置器",this,BorderLayout.CENTER);
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 20, 20));
        this.add(buttonPanel,BorderLayout.SOUTH);
        addButton = new ButtonOverride("增加标签", buttonPanel,BorderLayout.SOUTH, addEvent -> model.addElement(tf_tagName.getValue()));
        deleteButton = new ButtonOverride("移除选中标签", buttonPanel,BorderLayout.SOUTH, deleteEvent -> {
            try {
                model.remove(tagsList.getSelectedIndex());
            }catch (ArrayIndexOutOfBoundsException AOF){
                StaticUtil.errorReport.append(AOF.getMessage()+"\n");
                StaticUtil.errorReport.append("你目前没有选中一个可以删除的标签！\n");
                AOF.printStackTrace();
            }catch (Exception exception){
                exception.printStackTrace();
                StaticUtil.errorReport.append(exception.getMessage()+"\n");
            }
        });
        editButton = new ButtonOverride("编辑选中标签", buttonPanel,BorderLayout.SOUTH, editEvent ->{
            if (tagsList.isSelectionEmpty()){
                StaticUtil.errorReport.append("你目前没有选中一个可以编辑的标签！\n");
            }else {
                try{
                    model.set(tagsList.getSelectedIndex(),StaticUtil.StringChecker(JOptionPane.showInputDialog(frame,"请输入新的标签名",model.get(tagsList.getSelectedIndex())),model.get(tagsList.getSelectedIndex()),"输入的标签值不合法！"));
                }catch (ArrayIndexOutOfBoundsException AOF){
                    StaticUtil.errorReport.append(AOF.getMessage()+"\n");
                    StaticUtil.errorReport.append("你目前没有选中一个可以编辑的标签！\n");
                    AOF.printStackTrace();
                }catch (Exception exception){
                    exception.printStackTrace();
                    StaticUtil.errorReport.append(exception.getMessage()+"\n");
                }
            }
        });
        component.add(this);
    }

    public Object[] getValue(){
        return model.toArray();
    }
}
